from django.test import TestCase
from django.contrib.auth.models import User
from django.core.files.uploadedfile import SimpleUploadedFile
from rest_framework.test import APITestCase
from rest_framework import status
from .models import ResumeAnalysis
from .services.resume_analyzer import ResumeAnalyzer
import tempfile
import os


class ResumeAnalyzerTestCase(TestCase):
    """简历分析器测试用例"""
    
    def setUp(self):
        self.analyzer = ResumeAnalyzer()
    
    def test_extract_basic_info(self):
        """测试基本信息提取"""
        text = """
        张三的个人简历
        
        姓名：张三
        电话：13800138000
        邮箱：zhangsan@example.com
        出生日期：1990-01-01
        """
        
        info = self.analyzer._extract_basic_info(text)
        
        self.assertEqual(info['name'], '张三')
        self.assertEqual(info['phone'], '13800138000')
        self.assertEqual(info['email'], 'zhangsan@example.com')
        self.assertEqual(info['birth_date'], '1990-01-01')
    
    def test_extract_skills(self):
        """测试技能提取"""
        text = """
        技能：
        Python, Java, JavaScript, React, Django, MySQL
        """
        
        skills = self.analyzer._extract_skills(text)
        
        expected_skills = ['Python', 'Java', 'JavaScript', 'React', 'Django', 'MySQL']
        for skill in expected_skills:
            self.assertIn(skill, skills)
    
    def test_generate_improvement_suggestions(self):
        """测试改进建议生成"""
        analysis = {
            'basic_info': {'name': '张三'},
            'education': [],
            'work_experience': [],
            'skills': ['Python'],
            'projects': [],
            'summary': {'total_words': 100}
        }
        
        suggestions = self.analyzer._generate_improvement_suggestions(analysis)
        
        self.assertIsInstance(suggestions, list)
        self.assertGreater(len(suggestions), 0)
    
    def test_recommend_positions(self):
        """测试职位推荐"""
        analysis = {
            'skills': ['Python', 'Django'],
            'work_experience': [{'position': 'Python开发工程师'}]
        }
        
        positions = self.analyzer._recommend_positions(analysis)
        
        self.assertIsInstance(positions, list)
        self.assertGreater(len(positions), 0)
    
    def test_recommend_companies(self):
        """测试公司推荐"""
        analysis = {
            'skills': ['Python', '机器学习']
        }
        
        companies = self.analyzer._recommend_companies(analysis)
        
        self.assertIsInstance(companies, list)
        self.assertGreater(len(companies), 0)


class ResumeAnalysisAPITestCase(APITestCase):
    """简历分析API测试用例"""
    
    def setUp(self):
        self.user = User.objects.create_user(
            username='testuser',
            password='testpass123'
        )
        self.client.force_authenticate(user=self.user)
    
    def test_create_resume_analysis(self):
        """测试创建简历分析"""
        # 创建测试文件
        content = "张三的个人简历\n姓名：张三\n技能：Python, Django".encode('utf-8')
        file = SimpleUploadedFile(
            "test_resume.txt",
            content,
            content_type="text/plain"
        )
        
        data = {
            'resume_file': file,
            'original_filename': 'test_resume.txt'
        }
        
        response = self.client.post('/api/resume/analysis/', data, format='multipart')
        
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
        self.assertIn('id', response.data)
        self.assertEqual(response.data['status'], 'pending')
    
    def test_get_analysis_status(self):
        """测试获取分析状态"""
        # 创建分析记录
        analysis = ResumeAnalysis.objects.create(
            user=self.user,
            resume_file=SimpleUploadedFile("test.txt", b"test content"),
            original_filename="test.txt",
            status='completed'
        )
        
        response = self.client.get(f'/api/resume/analysis/{analysis.id}/status/')
        
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['status'], 'completed')
    
    def test_get_analysis_statistics(self):
        """测试获取分析统计"""
        # 创建多个分析记录
        ResumeAnalysis.objects.create(
            user=self.user,
            resume_file=SimpleUploadedFile("test1.txt", b"test content"),
            original_filename="test1.txt",
            status='completed'
        )
        ResumeAnalysis.objects.create(
            user=self.user,
            resume_file=SimpleUploadedFile("test2.txt", b"test content"),
            original_filename="test2.txt",
            status='failed'
        )
        
        response = self.client.get('/api/resume/analysis/statistics/')
        
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['total_count'], 2)
        self.assertEqual(response.data['completed_count'], 1)
        self.assertEqual(response.data['failed_count'], 1)
    
    def test_file_validation(self):
        """测试文件验证"""
        # 测试不支持的文件格式
        content = b"test content"
        file = SimpleUploadedFile(
            "test_resume.exe",
            content,
            content_type="application/octet-stream"
        )
        
        data = {
            'resume_file': file,
            'original_filename': 'test_resume.exe'
        }
        
        response = self.client.post('/api/resume/analysis/', data, format='multipart')
        
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertIn('不支持的文件格式', str(response.data))
    
    def test_file_size_validation(self):
        """测试文件大小验证"""
        # 创建超过10MB的文件
        large_content = b"x" * (11 * 1024 * 1024)  # 11MB
        file = SimpleUploadedFile(
            "large_resume.txt",
            large_content,
            content_type="text/plain"
        )
        
        data = {
            'resume_file': file,
            'original_filename': 'large_resume.txt'
        }
        
        response = self.client.post('/api/resume/analysis/', data, format='multipart')
        
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
        self.assertIn('文件大小不能超过10MB', str(response.data))
